package backend_agent

import (
	"context"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentListLogic {
	return AgentListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentListLogic) AgentList(req *types.AgentListReq) (resp *respx.PageResp, err error) {
	list, err := l.svcCtx.AgentRpc.AgentList(l.ctx, &agentClient.AgentListReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Keyword:  req.Keyword,
		Status:   req.Status,
	})
	if err != nil {
		return nil, err
	}

	res := make([]*types.AgentListResp, 0)
	for _, agent := range list.List {
		count, err := l.svcCtx.AgentRpc.StoreCount(l.ctx, &agentClient.StoreCountReq{
			AgentId: agent.Id,
			Status:  -1,
		})
		if err != nil {
			logx.Errorf("(agentID: %d)获取count失败: %s", agent.Id, err.Error())
			continue
		}
		temp := &types.AgentListResp{
			Id:         respx.IDFrom(agent.Id).ToString(),
			Nickname:   agent.Name,
			Phone:      agent.Phone,
			CreateTime: tools.TimeUnixShowLayoutString(agent.CreateTime),
			Status:     agent.Status,
			StoreCount: count.Count,
		}
		res = append(res, temp)
	}

	return respx.NewPageResp(req.Page, req.PageSize, list.Total, res), nil
}
